const express = require('express')
const fs = require('fs')
let path = require('path')
const response = require('../../utils/response')
const Task = require('../../models/task')

const archiver = require('archiver');

// 创建一个空的压缩包
const zlib = require('zlib')
const gzib = zlib.createGzip()
const router = express.Router()

// 生成日期
function add0(m) {
    return m < 10 ? '0' + m : m
}
var time = new Date();
var y = time.getFullYear();
var m = time.getMonth() + 1;
var d = time.getDate();
var h = time.getHours();
var mm = time.getMinutes();
var s = time.getSeconds();
m = add0(m)
d = add0(d)
h = add0(h)
mm = add0(mm)
s = add0(s)


// 文件下载
router.get('/downloadFile', async (req, res) => {
    let path = req.query.path
    let originalname = req.query.originalname
    var fileAddress = `${path}-${originalname}`
    try {
        fs.statSync(fileAddress)
        res.download(fileAddress)
    } catch (error) {
        response(res, 404, '没有找到该文件')
    }
})

// 文件删除
router.get('/deleteFile/:taskId', async (req, res) => {
    let path = req.query.path
    let originalname = req.query.originalname
    let taskId = req.params.taskId
    var task = await Task.findById(taskId)
    var fileAddress = `${path}-${originalname}`
    // console.log(path);
    try {
        fs.statSync(fileAddress)
        for (var i = 0; i < task.fileAddress.length; i++) {
            var address = task.fileAddress[i]
            if (address.files != '') {
                for (key in address.files) {
                    if (address.files[key] != null) {
                        if (path == address.files[key].path) {
                            // console.log(task.fileAddress[i].files[key]);
                            task.fileAddress[i].files.splice(key,1)
                        }
                    }
                }
            }
        }
        await task.save()
        fs.unlinkSync(fileAddress)
        response(res, 200, '删除文件成功', task)
    } catch (error) {
        console.log(error);
        response(res, 404, '没有找到该文件')
    }
})

// 文件测试
router.post('/deleteFileaaa', async (req, res) => {
    let taskId = req.body.taskId
    const task = await Task.findById(taskId)
    response(res, 200, '删除文件成功', task)
})



module.exports = router